package gossip;

import org.ricks.net.MessageProcessor;
import org.ricks.net.StateMachineEnum;
import org.ricks.net.extension.protocol.StringProtocol;
import org.ricks.net.transport.AioQuickClient;
import org.ricks.net.transport.AioQuickServer;
import org.ricks.net.transport.AioSession;

import java.io.IOException;
import java.net.InetSocketAddress;

public class GossipTransport {


    private final int port;
    private final GossipCore core;
    private AioQuickServer server;

    public GossipTransport(int port, GossipCore core) {
        this.port = port;
        this.core = core;
    }

    public void start() {
        server = new AioQuickServer(port, new StringProtocol(), new MessageProcessor<String>() {
            @Override
            public void process(AioSession session, String msg) {
                try {
                    core.handleMessage(session.getRemoteAddress(), msg);
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }

            @Override
            public void stateEvent(AioSession session, StateMachineEnum state, Throwable throwable) {
                if (state == StateMachineEnum.DECODE_EXCEPTION || state == StateMachineEnum.PROCESS_EXCEPTION) {
                    throwable.printStackTrace();
                }
            }
        });
        try {
            server.setReadBufferSize(1024).setThreadNum(2).start();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public void send(InetSocketAddress target, String data) {
        try {
            AioQuickClient client = new AioQuickClient(target.getHostName(), target.getPort(),
                    new StringProtocol(), (session, msg) -> {});
            AioSession session = client.start();
            session.writeBuffer().writeInt(4 + data.getBytes().length);
            session.writeBuffer().write(data.getBytes());
            session.writeBuffer().flush();
            Thread.sleep(10); // 确保消息发送完成
            client.shutdown();
        } catch (Exception e) {
            System.err.println("Failed to send message to " + target + ": " + e.getMessage());
        }
    }
}
